package common

import (
	"../global/utils"
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"

	jsoniter "github.com/json-iterator/go"
)

// GETLongTime 发送GET请求 60 秒超时
func GETLongTime(url string) (resp []byte, err error) {
	client := http.DefaultClient
	client.Timeout = 60 * time.Second
	response, err := client.Get(url)
	if err != nil {
		return
	}
	resp, err = ioutil.ReadAll(response.Body)
	if err != nil {
		return
	}
	return
}

// GET 发送GET请求
func GET(url string) (resp []byte, err error) {
	client := http.DefaultClient
	client.Timeout = 10 * time.Second
	response, err := client.Get(url)
	if err != nil {
		return
	}
	resp, err = ioutil.ReadAll(response.Body)
	if err != nil {
		return
	}

	return
}

// POST ...
func POSTJson(url string, body ...interface{}) (resp []byte, err error) {
	client := http.DefaultClient
	client.Timeout = 10 * time.Second
	var buf []byte
	if len(body) > 0 {
		buf, err = jsoniter.Marshal(body[0])
		if err != nil {
			return
		}
	}
	response, err := client.Post(url, "application/json", bytes.NewReader(buf))
	if err != nil {
		return
	}
	resp, err = ioutil.ReadAll(response.Body)
	if err != nil {
		return
	}

	return
}

func BuildURI(data interface{}) (res string) {
	dataMap := make(map[string]interface{}, 0)
	jsonBytes, _ := json.Marshal(data)
	_ = json.Unmarshal(jsonBytes, &dataMap)

	uri := new(url.URL)
	q := uri.Query()
	for k, v := range dataMap {
		q.Add(k, ToString(v))
	}
	res = q.Encode()
	return
}

func CmmApi(reqType string, uri string, params map[string]interface{}) (resBody []byte, resp *http.Response, err error) {
	var req *http.Request
	client := http.DefaultClient
	client.Timeout = 10 * time.Second
	reqType = strings.ToUpper(reqType)
	switch reqType {
	case "GET":
		query := "?"
		if len(params) > 0 {
			for k, v := range params {
				query += k + "=" + utils.ToString(v) + "&"
			}
			uri = uri + query[:len(query)-1]
		}
		req, err = http.NewRequest("GET", uri, nil)
	case "POST":
		var body io.Reader
		if len(params) > 0 {
			jsonByte, _ := json.Marshal(params)
			body = bytes.NewReader(jsonByte)
		}
		req, err = http.NewRequest("POST", uri, body)
	}
	if err != nil {
		return
	}
	req.Header.Add("Content-Type", "application/json;charset=UTF-8")
	resp, err = client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	if resp.StatusCode == 200 {
		resBody, err = io.ReadAll(resp.Body)
		if err == nil && jsoniter.Get(resBody, "errCode").ToInt() != 0 {
			err = errors.New("数据服务异常")
		}
	} else {
		err = errors.New("数据服务异常")
	}
	return
}
